package com.zzc.interview.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.zzc.interview.annotation.AuthCheck;
import com.zzc.interview.common.BaseResponse;
import com.zzc.interview.common.DeleteRequest;
import com.zzc.interview.common.ErrorCode;
import com.zzc.interview.common.ResultUtils;
import com.zzc.interview.constant.UserConstant;
import com.zzc.interview.exception.BusinessException;
import com.zzc.interview.exception.ThrowUtils;
import com.zzc.interview.model.dto.ojQuestion.OjQuestionAddRequest;
import com.zzc.interview.model.dto.ojQuestion.OjQuestionEditRequest;
import com.zzc.interview.model.dto.ojQuestion.OjQuestionQueryRequest;
import com.zzc.interview.model.dto.ojQuestion.OjQuestionUpdateRequest;
import com.zzc.interview.model.entity.OjQuestion;
import com.zzc.interview.model.entity.User;
import com.zzc.interview.model.vo.OjQuestionVO;
import com.zzc.interview.service.OjQuestionService;
import com.zzc.interview.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 *
 */
@RestController
@RequestMapping("/ojQuestion")
@Slf4j
public class OjQuestionController {

    @Resource
    private OjQuestionService questionService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param ojQuestionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestion(@RequestBody OjQuestionAddRequest ojQuestionAddRequest, HttpServletRequest request) {
        if (ojQuestionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        OjQuestion question = new OjQuestion();
        BeanUtils.copyProperties(ojQuestionAddRequest, question);
        List<String> tags = ojQuestionAddRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        questionService.validOjQuestion(question, true);
        User loginUser = userService.getLoginUser(request);
        question.setUserId(loginUser.getId());
        question.setFavourNum(0);
        question.setThumbNum(0);
        question.setJudgeConfig(JSONUtil.toJsonStr(ojQuestionAddRequest.getJudgeConfig()));
        question.setJudgeCase(JSONUtil.toJsonStr(ojQuestionAddRequest.getJudgeCase()));
        boolean result = questionService.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        OjQuestion oldOjQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldOjQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldOjQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = questionService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody OjQuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        OjQuestion question = new OjQuestion();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        List<String> tags = questionUpdateRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        // 参数校验
        questionService.validOjQuestion(question, false);
        long id = questionUpdateRequest.getId();
        // 判断是否存在
        OjQuestion oldOjQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldOjQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<OjQuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        OjQuestion question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 用户信息
        Long userId = question.getUserId();
        User user = userService.getById(userId);
        return ResultUtils.success(questionService.getOjQuestionVO(question, user));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<OjQuestionVO>> listQuestionVOByPage(@RequestBody OjQuestionQueryRequest questionQueryRequest,
            HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<OjQuestion> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 用户信息
        Long userId = questionQueryRequest.getUserId();
        User user = userService.getById(userId);
        return ResultUtils.success(questionService.getOjQuestionVOPage(questionPage, user));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<OjQuestionVO>> listMyQuestionVOByPage(@RequestBody OjQuestionQueryRequest questionQueryRequest,
            HttpServletRequest request) {
        if (questionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<OjQuestion> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 用户信息
        Long userId = questionQueryRequest.getUserId();
        User user = userService.getById(userId);
        return ResultUtils.success(questionService.getOjQuestionVOPage(questionPage, user));
    }

    /**
     * 根据题目id返回题目
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/getOne")
    public BaseResponse<OjQuestion> getQuestionById(@RequestParam Integer id, HttpServletRequest request) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        OjQuestion question = questionService.getById(id);
        return ResultUtils.success(question);
    }

    /**
     * 管理员获取数据库中的所有题目信息
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/all")
    public BaseResponse<Page<OjQuestion>> listMyQuestionByPage(@RequestBody OjQuestionQueryRequest questionQueryRequest,
                                                                   HttpServletRequest request) {
        if (questionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<OjQuestion> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 用户信息
        Long userId = questionQueryRequest.getUserId();
        User user = userService.getById(userId);
        return ResultUtils.success(questionService.getOjQuestionPage(questionPage, user));
    }

    /**
     * 编辑题目信息
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody OjQuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        OjQuestion question = new OjQuestion();
        BeanUtils.copyProperties(questionEditRequest, question);
        List<String> tags = questionEditRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        // 测试用例赋值
        question.setJudgeCase(JSONUtil.toJsonStr(questionEditRequest.getJudgeCase()));
        // 配置赋值
        question.setJudgeConfig(JSONUtil.toJsonStr(questionEditRequest.getJudgeConfig()));
        // 参数校验
        questionService.validOjQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        long id = questionEditRequest.getId();
        // 判断是否存在
        OjQuestion oldOjQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldOjQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldOjQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

}
